package com.zjut.zs.exvalue.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.zjut.an.util.module.PageModule;
import com.zjut.zs.userinfo.dao.ZsUserinfo;

/**
 * A data access object (DAO) providing persistence and search support for
 * ZsExValue entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.zjut.zs.exvalue.dao.ZsExValue
 * @author MyEclipse Persistence Tools
 */

public class ZsExValueDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory
			.getLogger(ZsExValueDAO.class);
	// property constants
	public static final String EXV_ID = "exvId";
	public static final String SC_CODE = "scCode";
	public static final String COLUMN1 = "column1";
	public static final String COLUMN2 = "column2";
	public static final String COLUMN3 = "column3";
	public static final String COLUMN4 = "column4";
	public static final String COLUMN5 = "column5";
	public static final String COLUMN6 = "column6";
	public static final String COLUMN7 = "column7";
	public static final String COLUMN8 = "column8";
	public static final String COLUMN9 = "column9";
	public static final String COLUMN10 = "column10";

	protected void initDao() {
		// do nothing
	}

	public void sort(Criteria criteria, String sort, String order) {
		if (sort!=null && order!=null) {
			if (order.equals("asc")) {
				criteria.addOrder(Order.asc(sort));
			} else {
				criteria.addOrder(Order.desc(sort));
			}
		} else {
			criteria.addOrder(Order.desc(EXV_ID));			
		}
	}
	
	public void save(ZsExValue transientInstance) {
		log.debug("saving ZsExValue instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void update(ZsExValue transientInstance) {
		log.debug("updating ZsExValue instance");
		try {
			getHibernateTemplate().update(transientInstance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}
	
	public void delete(ZsExValue persistentInstance) {
		log.debug("deleting ZsExValue instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public ZsExValue findById(java.lang.String id) {
		log.debug("getting ZsExValue instance with id: " + id);
		try {
			ZsExValue instance = (ZsExValue) getHibernateTemplate().get(
					"com.zjut.zs.exvalue.dao.ZsExValue", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(ZsExValue instance) {
		log.debug("finding ZsExValue instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding ZsExValue instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from ZsExValue as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByScCode(Object scCode) {
		return findByProperty(SC_CODE, scCode);
	}

	public List findByColumn1(Object column1) {
		return findByProperty(COLUMN1, column1);
	}

	public List findByColumn2(Object column2) {
		return findByProperty(COLUMN2, column2);
	}

	public List findByColumn3(Object column3) {
		return findByProperty(COLUMN3, column3);
	}

	public List findByColumn4(Object column4) {
		return findByProperty(COLUMN4, column4);
	}

	public List findByColumn5(Object column5) {
		return findByProperty(COLUMN5, column5);
	}

	public List findByColumn6(Object column6) {
		return findByProperty(COLUMN6, column6);
	}

	public List findByColumn7(Object column7) {
		return findByProperty(COLUMN7, column7);
	}

	public List findByColumn8(Object column8) {
		return findByProperty(COLUMN8, column8);
	}

	public List findByColumn9(Object column9) {
		return findByProperty(COLUMN9, column9);
	}

	public List findByColumn10(Object column10) {
		return findByProperty(COLUMN10, column10);
	}

	public List findAll() {
		log.debug("finding all ZsExValue instances");
		try {
			String queryString = "from ZsExValue";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public ZsExValue merge(ZsExValue detachedInstance) {
		log.debug("merging ZsExValue instance");
		try {
			ZsExValue result = (ZsExValue) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(ZsExValue instance) {
		log.debug("attaching dirty ZsExValue instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(ZsExValue instance) {
		log.debug("attaching clean ZsExValue instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static ZsExValueDAO getFromApplicationContext(ApplicationContext ctx) {
		return (ZsExValueDAO) ctx.getBean("ZsExValueDAO");
	}

	@SuppressWarnings("unchecked")
	public PageModule findByInstance(final int pageNumber ,final int pageSize, String sort, String order, final ZsExValue obj){
		try {
			int startIndex = (pageNumber - 1) * pageSize;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			List list;
			Criteria criteria = session.createCriteria(ZsExValue.class);
			 
			if (!isEmpty(obj.getScCode())) {
				criteria.add(Restrictions.like(SC_CODE, obj.getScCode(),MatchMode.ANYWHERE));
			}
			if (null != obj.getZsUser()) {
				criteria.add(Restrictions.eq("zsUser", obj.getZsUser()));
			}
			if (!isEmpty(obj.getColumn1())) {
				criteria.add(Restrictions.like(COLUMN1, obj.getColumn1(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn2())) {
				criteria.add(Restrictions.like(COLUMN2, obj.getColumn2(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn3())) {
				criteria.add(Restrictions.like(COLUMN3, obj.getColumn3(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn4())) {
				criteria.add(Restrictions.like(COLUMN4, obj.getColumn4(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn5())) {
				criteria.add(Restrictions.like(COLUMN5, obj.getColumn5(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn6())) {
				criteria.add(Restrictions.like(COLUMN6, obj.getColumn6(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn7())) {
				criteria.add(Restrictions.like(COLUMN7, obj.getColumn7(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn8())) {
				criteria.add(Restrictions.like(COLUMN8, obj.getColumn8(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn9())) {
				criteria.add(Restrictions.like(COLUMN9, obj.getColumn9(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn10())) {
				criteria.add(Restrictions.like(COLUMN10, obj.getColumn10(),MatchMode.ANYWHERE));
			}
			//补充
			
			this.sort(criteria, sort, order);
			
			criteria.setFirstResult(startIndex);
			criteria.setMaxResults(pageSize);
			list = criteria.list();
			session.close();
			return new PageModule(pageNumber, pageSize, countByInstance(obj), list);
		} catch (RuntimeException re) {
			log.error("findByInstance failed", re);
			throw re;
		}
	}
	
	public int countByInstance(final ZsExValue obj) {
		log.debug("finding the number of ZsExValue instance");
		try {
			int count = 0;
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			Criteria criteria = session.createCriteria(ZsExValue.class);
			
			if (!isEmpty(obj.getScCode())) {
				criteria.add(Restrictions.like(SC_CODE, obj.getScCode(),MatchMode.ANYWHERE));
			}
			if (null != obj.getZsUser()) {
				criteria.add(Restrictions.eq("zsUser", obj.getZsUser()));
			}
			if (!isEmpty(obj.getColumn1())) {
				criteria.add(Restrictions.like(COLUMN1, obj.getColumn1(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn2())) {
				criteria.add(Restrictions.like(COLUMN2, obj.getColumn2(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn3())) {
				criteria.add(Restrictions.like(COLUMN3, obj.getColumn3(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn4())) {
				criteria.add(Restrictions.like(COLUMN4, obj.getColumn4(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn5())) {
				criteria.add(Restrictions.like(COLUMN5, obj.getColumn5(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn6())) {
				criteria.add(Restrictions.like(COLUMN6, obj.getColumn6(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn7())) {
				criteria.add(Restrictions.like(COLUMN7, obj.getColumn7(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn8())) {
				criteria.add(Restrictions.like(COLUMN8, obj.getColumn8(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn9())) {
				criteria.add(Restrictions.like(COLUMN9, obj.getColumn9(),MatchMode.ANYWHERE));
			}
			if (!isEmpty(obj.getColumn10())) {
				criteria.add(Restrictions.like(COLUMN10, obj.getColumn10(),MatchMode.ANYWHERE));
			}
			//补充
			
			count = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
			session.close();
			return count;
		} catch (RuntimeException re) {
			log.error("find the number of ZsExValue instance failed", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List findByHql(final int pageNumber ,final int pageSize, final String hql, final Object[] values){
		log.debug("finding ZsExValue instance by hql");
	    return (List<ZsExValue>) super.getHibernateTemplate().execute(new HibernateCallback(){
	        public Object doInHibernate(Session session) throws HibernateException, SQLException {
	            Query query=session.createQuery(hql);
	            if (values != null) {// 为hql语句传入参数
					for (int i = 0; i < values.length; i++) {
						query.setParameter(i, values[i]);
					}
				}
	            return query.setFirstResult((pageNumber-1)*pageSize).setMaxResults(pageSize).list();
	        }
	    });
	}

	@SuppressWarnings("unchecked")
	public int findCountByHql(final String hql, final Object[] values) {
		log.debug("finding the number of ZsExValue instance");
		try {
			return (Integer) super.getHibernateTemplate().execute(new HibernateCallback(){
		        public Object doInHibernate(Session session) throws HibernateException, SQLException {
		            Query query=session.createQuery(hql);
		            if (values != null) {// 为hql语句传入参数
						for (int i = 0; i < values.length; i++) {
							query.setParameter(i, values[i]);
						}
					}
					return ((Long)query.uniqueResult()).intValue();
		        }
		    });
		} catch (RuntimeException re) {
			log.error("find the number of ZsExValue instance failed", re);
			throw re;
		}
	}
	
	private boolean isEmpty(String value) {
		if (value==null || value.trim().length()==0) {
			return true;
		}
		return false;
	}
}